package com.group.voting_system.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.group.voting_system.entity.Vote;
import com.group.voting_system.service.IVoteService;
import com.group.voting_system.utils.RestResult;
import com.group.voting_system.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  逻辑控制器
 *  投票事件的增删改查都写在这里
 * </p>
 *
 * @author xyf
 * @since 2019-04-15
 */
@Controller
@RequestMapping("/vote")
public class VoteController {

    @Autowired
    IVoteService voteService;

    @GetMapping("/list")
    public String list(){
        return "vote/list";
    }

    @GetMapping("/add")
    public String add(){
        return "vote/add";
    }

    @GetMapping("/edit")
    public String edit(){ return "vote/edit"; }

    @GetMapping("/file/{vid}")
    public String file(@PathVariable("vid") Integer vid, Model model){
        model.addAttribute("vid", vid);
        return "vote/new_notice";
    }

    @PostMapping("")
    @ResponseBody
    public RestResult insert(@RequestBody Vote vote, HttpServletRequest request){
        boolean add = voteService.addOneVote(vote, request);
        if (!add)
            return ResultUtil.fail("添加失败");
        return ResultUtil.success("添加成功");
    }

    @PutMapping("")
    @ResponseBody
    public RestResult revise(@RequestBody Vote vote){
        boolean b = voteService.updateById(vote);
        if (!b)
            return ResultUtil.fail("修改失败");
        return ResultUtil.success("修改成功");
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public RestResult del(@PathVariable("id") Integer id){
        boolean b = voteService.removeById(id);
        if (!b)
            return ResultUtil.fail("删除失败");
        return ResultUtil.success("删除成功");
    }

    @GetMapping("")
    @ResponseBody
    public RestResult get(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                          @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize){
        IPage<Vote> page = voteService.page(new Page<Vote>(pageNo, pageSize).setDesc("id"));
        return ResultUtil.success("", page);
    }
}